/*
Copyright © 2022 NAME HERE <EMAIL ADDRESS>
*/
package cmd

import (
	"log"
	"net/http"
	"text/template"

	"gitee.com/liaojin0910/jin/elf"
	"github.com/spf13/cobra"
)

func IndexHandler(w http.ResponseWriter, r *http.Request) {
	var p = r.FormValue("p")
	if p == "" {
		p = "start.json"
	}
	var re = elf.Run(p)

	t1, err := template.ParseFiles("tpl/elf_header.html")
	if err != nil {
		http.Error(w, "解析模板失败", 200)
	}

	var out = &elf.Out{}
	out.Nav = p
	out.Rdata = re
	t1.Execute(w, out)

}

// elfHeaderCmd represents the elfHeader command
var elfHeaderCmd = &cobra.Command{
	Use:   "elfHeader",
	Short: "通过指定的json文件，分析查看elf文件格式",
	Run: func(cmd *cobra.Command, args []string) {
		//
		if len(args) < 1 {
			log.Fatalln("参数给定文件不对")
		}

		elf.Init(args[0], args[1])
		http.HandleFunc("/", IndexHandler)
		http.ListenAndServe("127.0.0.1:8999", nil)
	},
}

func init() {
	rootCmd.AddCommand(elfHeaderCmd)
}
